import Util.TreeNode;

import java.util.*;

/**
 * 二叉树层序遍历，用BFS思想实现
 */
public class levelOrder {

    public List<List<Integer>> levelOrderTraversal(TreeNode root){
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();

        if (root != null)
            queue.add(root);

        while (!queue.isEmpty()){
            int n = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < n; i++){
                TreeNode node = queue.remove();
                level.add(node.val);
                if (node.left != null)
                    queue.add(node.left);
                if (node.right != null)
                    queue.add(node.right);
            }
            res.add(level);
        }
        return res;
    }
}
